package com.mybatisplus.mp.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mybatisplus.mp.mapper.UserMapper;
import com.mybatisplus.mp.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Spring事务三大接口 PlatformTransactionManager:(平台)事务管理器 模板方法设计模式
 * TransactionDefinition:事务定义信息（事务隔离级别、传播行为、超时、只读、回滚规则）
 * TransactionStatus：事务运行状态
 * <p>
 * 如果在同一个类，这样的传播写法，注解是不生效的。
 * 如果在同一个类中也可以,需要从上下文容器中重新获取一次bean,再调methodB即可
 */
@Service
@Slf4j

public class UserService {
    @Autowired
    SqlSession sqlSession;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService2 userService2;

    //    @Cacheable
    public User get(Integer id) {
        log.info("--0--------------------" + "进入业务层");
        User user = userMapper.selectById(id);
        return user;
    }

    public void t() {

    }

    @Transactional
    public void testA() {

        testB();
        userService2.testC();
        /*tryb {
            throw new RuntimeException();
        } catch (RuntimeException e) {

        }*/
//        throw new  RuntimeException("故意的");

    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void testB() {
        User build1 = User.builder().version(1)
                .name("testB").build();
        userMapper.insert(build1);
//        throwErr();
//        throw new RuntimeException();

    }

    private void throwErr() {
        throw new RuntimeException();
    }

    @Transactional
    public Object test() {
        User user = userMapper.selectById(1L);
        System.out.println(user);
        return user;
    }

    @Transactional
    public Object test2() throws InterruptedException {
        User user = User.builder().name("测试数据").build();
        userMapper.insert(user);
        Thread.sleep(100000L);
        return user;
    }


    @Transactional
    public String versionTest() {
        System.out.println("进入————————————————————————————————");
        User user = userMapper.selectById(1);
        try {
            Thread.sleep(10000L);
        } catch (Exception e) {
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", 1);
        int update = userMapper.update(user, wrapper);
        User build = User.builder().build();
        userMapper.insertInto(build);
        if (update!=1) {
            throw new RuntimeException();
        }
        return "ok";
    }
}
